package com.myrabbitmqdemo.demo.one;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeoutException;

/**
 *
 * @author asue
 * 消费者 接收消息的
 */
public class Consumer {
    // 队列名称
    public static final String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("121.5.192.204");

        factory.setUsername("admin");

        factory.setPassword("123");

        Connection connection = factory.newConnection();

        Channel channel1 = connection.createChannel();

        // 声明
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                System.out.println(new String(delivery.getBody()));
                System.out.println("消息已经被接收");
            }
        };

//        DeliverCallback deliverCallback = (consumerTag,message) -> {
//            System.out.println(message);
//        };

        //取消消息的回调
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("消息消费被中断");
        };


        /**
         * 消费者消费消息
         * 1、表示消费哪个队列
         * 2、消费成功之后是否自动应答，true自动应答，false收到应答
         * 3、消费者未成功消费的回调
         * 4、消费者取消消费的回调
         */
        channel1.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
    }

}
